#!/bin/sh

. "$SPEC_PATH/abstract/backup"

e2e_test_extra_hash() {
  "$SHELL" "$PROJECT_PATH/stackgres-k8s/ci/build/build-functions.sh" path_hash \
    "$(realpath --relative-to "$PROJECT_PATH" "$SPEC_PATH/abstract/backup")"
}

e2e_test_install() {
  install_minio

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 2

  deploy_curl_pod "$CLUSTER_NAMESPACE"

  wait_pods_running "$CLUSTER_NAMESPACE" 4
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
  switch_cluster_to_first "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"

  # Avoid backups before waiting for pods (since backup pods could biase the wait)
  enable_cluster_cron_schedule
}

e2e_test() {
  run_test "Checking that switchover is working" check_switchover

  run_test "Checking that backup is working after switchover" check_backup_after_switchover

  run_test "Checking that backup retention is working after switchover" check_backup_retention_after_switchover
}

check_cron_job_security_context() {
  local RUN_AS_NON_ROOT
  RUN_AS_NON_ROOT="$(kubectl get cronjobs.batch -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME"-backup -o jsonpath='{.spec.jobTemplate.spec.template.spec.securityContext.runAsNonRoot}')"
  assert_string_equal "true" "$RUN_AS_NON_ROOT"
}


check_backup_retention_after_switchover() {
  check_backup_retention 1
}

check_backup_after_switchover() {
  kubectl delete job -n "$CLUSTER_NAMESPACE" -l "stackgres.io/scheduled-backup=true"

  check_backup 1
}

check_switchover() {
  PATRONI_MAJOR_VERSION="$(kubectl exec -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-0" -c patroni -- \
    patronictl version 2>/dev/null | sed -n 's/^patronictl version \([0-9]\+\)\..*$/\1/p')"
  if kubectl exec -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME"-0 -c patroni -- \
    patronictl switchover \
      $([ "$PATRONI_MAJOR_VERSION" -lt 4 ] && printf %s --master || printf %s --primary) "$CLUSTER_NAME"-0 \
      --candidate "$CLUSTER_NAME"-1 --force
  then
    success "The switchover has been performed"
  else
    fail "The switchover operation failed"
  fi

  if wait_until run_query -i 0 -p 5432
  then
    success "The replica becomed available"
  else
    fail "The replica is not available"
  fi

  if ! run_query -i 1 -p 5432 -q "SELECT pg_is_in_recovery()" | grep -q '^t$'
  then
    success "The primary is now the node at index 1"
  else
    fail "The node at index 1 is not the primary"
  fi

  if ! run_query -i 0 -p 5432 -q "SELECT pg_is_in_recovery()" | grep -q '^f$'
  then
    success "The replica is now the node at index 0"
  else
    fail "The node at index 0 is not a replica"
  fi
}

